package com.zzw.zim.config;

import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

/**
 * <p>项目名称: zzw-tech </p>
 * <p>包名称: com.zzw.mis.config </p>
 * <p>描述: 跨域配置 </p>
 * <p> 跨域配置 </p>
 * <p>创建时间: 2022/11/15 14 </p>
 *
 * @author coco
 * @version v1.0
 */
// @Configuration
public class CorsConfig {
	private static final String MAX_AGE = "18000L";

	// @Bean
	// public WebFilter corsFilter () {
	// 	return (ServerWebExchange ctx, WebFilterChain chain) -> {
	// 		ServerHttpRequest request = ctx.getRequest();
	// 		if (!CorsUtils.isCorsRequest(request)) {
	// 			return chain.filter(ctx);
	// 		}
	// 		HttpHeaders requestHeaders = request.getHeaders();
	// 		ServerHttpResponse response = ctx.getResponse();
	// 		HttpMethod requestMethod = requestHeaders.getAccessControlRequestMethod();
	// 		HttpHeaders headers = response.getHeaders();
	// 		headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, requestHeaders.getOrigin());
	// 		headers.addAll(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, requestHeaders.getAccessControlRequestHeaders());
	// 		if (requestMethod != null) {
	// 			headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.name());
	// 		}
	// 		headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
	// 		headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*");
	// 		headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, MAX_AGE);
	// 		if (request.getMethod() == HttpMethod.OPTIONS) {
	// 			response.setStatusCode(HttpStatus.OK);
	// 			return Mono.empty();
	// 		}
	// 		return chain.filter(ctx);
	// 	};
	// }

	// @Bean
	public CorsWebFilter corsWebFilter () {
		CorsConfiguration config = new CorsConfiguration();
		config.addAllowedMethod("*");
		// config.addAllowedOrigin("*");
		config.addAllowedOriginPattern("*");
		config.addAllowedHeader("*");

		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
		source.registerCorsConfiguration("/**", config);

		return new CorsWebFilter(source);
	}

}
